<template>
	<div class="layout-padding">
		<splitpanes>
			<pane max-size="39" size="30" min-size="30">
				<div class="layout-padding-auto layout-padding-view left_greenhouse">
					<el-row  justify="space-between">
						<el-col :span="8">
              <div class="pane_title">
                <p>种植大棚</p>
              </div>
            </el-col>
            <el-col :span="16">
              <el-form-item>
                <div style="width:100%;display: flex;justify-content: flex-end">
                  <el-button icon="search" type="primary" @click="thisPageState.greenHouseMethods.getDataList"> 查询 </el-button>
                  <el-button icon="Refresh" @click="thisPageState.greenHouseMethods.resetQuery">重置</el-button>
                </div>
              </el-form-item>
            </el-col>
					</el-row>
					<el-row v-show="greenHouseShowSearch">
						<el-form
							:model="thisPageState.greenHouseState.queryForm"
							ref="greenHouseQueryRef"
							:inline="true"
							@keyup.enter="thisPageState.greenHouseMethods.getDataList"
						>
              <!--              label="所属基地"-->
              <el-form-item  prop="baseinfoId" style="width: 100%">
                <el-select v-model="thisPageState.greenHouseState.queryForm.baseinfoId" placeholder="请选择所属基地">
                  <el-option :key="index" :label="item.baseName" :value="item.id" v-for="(item, index) in thisPageState.baseInfoList"></el-option>
                </el-select>
              </el-form-item>
<!--              label="大棚名称"-->
							<el-form-item  prop="houseName"  style="width: 100%">
								<el-input placeholder="请输入大棚名称" v-model="thisPageState.greenHouseState.queryForm.houseName" />
							</el-form-item>
						</el-form>
					</el-row>
					<el-scrollbar height="100%">
						<div class="greenhouse_item_wrap" v-loading="thisPageState.greenHouseState.loading">
							<!--              :class="'house_item ' + thisPageState.deviceState.queryForm.greenhouseId===item.id ? ' house_item_active' : ''"-->
							<template v-for="(item, index) in thisPageState.greenHouseState.dataList">
								<div
									:class="'house_item ' + (thisPageState.deviceState.queryForm.greenhouseId === item.id ? 'house_item_active' : '')"
									@click="selectGreenHouse(item)"
								>
									<div>{{ item.houseName }}</div>
									<div>{{ item.houseArea }}</div>
								</div>
							</template>
						</div>
					</el-scrollbar>
					<!--          <pagination @size-change="thisPageState.greenHouseMethods.sizeChangeHandle" @current-change="thisPageState.greenHouseMethods.currentChangeHandle" v-bind="thisPageState.greenHouseState.pagination"/>-->
				</div>
			</pane>
			<pane class="ml-1">
        <div class="layout-padding-auto layout-padding-view">
          <el-row  justify="space-between" style="width: 100%" class="query_el_row-wrapper">
            <el-col :span="9">
              <div class="pane_title">
                <p>绑定设备</p>
              </div>
            </el-col>
            <el-col :span="7">
              <div class="query_button_wrap">
                <el-button icon="search" type="primary" @click="thisPageState.deviceMethods.getDataList">
                  查询
                </el-button>
                <el-button icon="Refresh" @click="thisPageState.deviceMethods.resetQuery">重置</el-button>
              </div>
            </el-col>
          </el-row>
          <el-scrollbar height="100%">
            <el-row v-show="houseDeviceShowSearch" class="query_el_row-wrapper">
              <el-col :span="17">
                <el-form
                    :model="thisPageState.deviceState.queryForm"
                    ref="houseDeviceQueryRef"
                    :inline="true"
                    @keyup.enter="thisPageState.deviceMethods.getDataList"
                >
                  <el-form-item label="设备名称" prop="deviceName">
                    <el-input placeholder="请输入设备名称" v-model="thisPageState.deviceState.queryForm.deviceName" />
                  </el-form-item>
                  <el-form-item label="设备编号" prop="deviceCode">
                    <el-input placeholder="请输入设备编号" v-model="thisPageState.deviceState.queryForm.deviceCode" />
                  </el-form-item>
                  <el-form-item label="设备在线状态" prop="deviceOnlineStatus">
                    <el-select v-model="thisPageState.deviceState.queryForm.deviceOnlineStatus" placeholder="请选择设备在线状态">
                      <el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in iot_device_online_status_dict"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="设备所在地址" prop="deviceAddress">
                    <el-input placeholder="请输入设备所在地址" v-model="thisPageState.deviceState.queryForm.deviceAddress" />
                  </el-form-item>
                  <el-form-item label="设备分类" prop="deviceCategoryId">
                    <el-select v-model="thisPageState.deviceState.queryForm.deviceCategoryId" placeholder="请选择设备分类">
                      <el-option
                          :key="index"
                          :label="item.categoryName"
                          :value="item.id"
                          v-for="(item, index) in thisPageState.deviceCategoryList"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="设备绑定状态" prop="deviceBindStatus">
                    <el-select v-model="thisPageState.deviceState.queryForm.deviceBindStatus" placeholder="请选择绑定状态">
                      <el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in iot_device_bind_status_dict"></el-option>
                    </el-select>
                  </el-form-item>

                </el-form>
              </el-col>

            </el-row>
            <el-row class="add_el_row_wrapper">
              <el-col :span="15" class="add_el_button_el_col">
                <div class="mb8" style="width: 100%">
                  <el-button :disabled="!thisPageState.deviceState.queryForm.greenhouseId" icon="folder-add" type="primary" class="ml10" @click="formDeviceDialogRef.openDialog()"
                             v-auth="'duorou_duorouGreenhouseDevice_add'">
                    新 增
                  </el-button>
                  <el-button plain :disabled="multipleDevice" icon="Delete" type="primary"
                             v-auth="'duorou_duorouGreenhouseDevice_del'" @click="handleBindDeviceDelete(selectDeviceObjs)">
                    删除
                  </el-button>
                </div>
              </el-col>
              <el-col :span="9" class="right_tool_el_col">
                <right-toolbar v-model:showSearch="houseDeviceShowSearch" :export="'iot_iotDevice_export'"
                               @exportExcel="exportBindDeviceExcel" class="ml10 mr20" style="float: right;"
                               @queryTable="thisPageState.deviceMethods.getDataList"></right-toolbar>
              </el-col>
            </el-row>
            <el-table
                :data="thisPageState.deviceState.dataList"
                v-loading="thisPageState.deviceState.loading"
                border
                :cell-style="thisPageState.deviceMethods.tableStyle.cellStyle"
                :header-cell-style="thisPageState.deviceMethods.tableStyle.headerCellStyle"
                @selection-change="selectionDeviceChangHandle"
                @sort-change="thisPageState.deviceMethods.sortChangeHandle"
            >
              <el-table-column type="selection"  />
              <el-table-column prop="deviceName" label="设备名称" show-overflow-tooltip />
              <el-table-column prop="deviceCode" label="设备编号" show-overflow-tooltip />
              <el-table-column prop="deviceImg" label="设备图片路径" show-overflow-tooltip />
              <el-table-column prop="deviceOnlineStatus" label="设备在线状态" show-overflow-tooltip>
                <template #default="scope">
                  <dict-tag :options="iot_device_online_status_dict" :value="scope.row.deviceOnlineStatus"></dict-tag>
                </template>
              </el-table-column>
              <el-table-column prop="deviceAddress" label="设备所在地址" show-overflow-tooltip />
              <el-table-column prop="deviceCategoryId" label="分类" show-overflow-tooltip />
              <el-table-column prop="deviceBindStatus" label="绑定状态" show-overflow-tooltip>
                <template #default="scope">
                  <dict-tag :options="iot_device_bind_status_dict" :value="scope.row.deviceBindStatus"></dict-tag>
                </template>
              </el-table-column>
              <el-table-column prop="deviceRemark" label="设备信息备注" show-overflow-tooltip />
              <el-table-column prop="createBy" label="创建者" show-overflow-tooltip />
              <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
              <el-table-column label="操作" width="130">
                <template #default="scope">
                  <el-button icon="Odometer" text type="primary"
                             @click="gotoDeviceRunData(scope.row,thisPageState.deviceState.queryForm.greenhouseId)">
                    运行数据
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
          <!--          <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />-->
        </div>
			</pane>
		</splitpanes>


    <!-- 编辑、新增  -->
    <form-device-dialog ref="formDeviceDialogRef" :greenHouseID="thisPageState.deviceState.queryForm.greenhouseId? thisPageState.deviceState.queryForm.greenhouseId : null" @refresh="thisPageState.deviceMethods.getDataList(false)" />
	</div>
</template>

<script setup lang="ts" name="smartGreenhouse">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList as fetchGreenhouseList } from '/@/api/farm/farmGreenhouse';
import { fetchList as fetchBaseInfoList } from '/@/api/farm/farmBaseinfo';
import { fetchList as fetchDeviceCategoryList } from "/@/api/iot/iotDeviceCategory";
import { fetchDeviceListByHouseID ,delObjs as delHouseDeviceObjs} from '/@/api/duorou/duorouGreenhouseDevice';

import { useMessage, useMessageBox } from '/@/hooks/message';
import { useDict } from '/@/hooks/dict';

const route = useRoute();
const router = useRouter();


/**
 *  左边种植大棚表格 搜索变量
 */
const greenHouseQueryRef = ref();
const greenHouseShowSearch = ref(true);

/**
 * 右边大棚绑定设备搜索变量
 */
const houseDeviceQueryRef = ref();
const houseDeviceShowSearch = ref(true);

/**
 * 去除模板中直接使用的statu自定义一个自己需要使用的 页面state
 */
const thisPageState = reactive({
	baseInfoList: [], //所有基地信息
	//种植大棚的表格状态
	greenHouseState: {
		queryForm: {},
		pageList: fetchGreenhouseList,
	},
	//  左边种植大棚的之前的方法等
	greenHouseMethods: {},

	deviceCategoryList: [], //所有设备分类
	//右边设备表格的状态
	deviceState: {
    isPage:false, //一个大棚下面设备不多，所以取消分页查询
		queryForm: {},
		pageList: fetchDeviceListByHouseID,
	},
	//右边设备 表格对应的方法
	deviceMethods: {},
});

/**
 * 左边种植大棚的方法 吧模板里面的提取出来
 *   //  table hook
 *   // const {
 *   //   getDataList,
 *   //   currentChangeHandle,
 *   //   sizeChangeHandle,
 *   //   sortChangeHandle,
 *   //   downBlobFile,
 *   //   tableStyle
 *   // } = useTable(state)
 *   // 清空搜索条件
 *   // const resetQuery = () => {
 *   //   // 清空搜索条件
 *   //   greenHouseQueryRef.value?.resetFields()
 *   //   getDataList()
 *   // }
 */
thisPageState.greenHouseMethods = useTable(thisPageState.greenHouseState);
thisPageState.greenHouseMethods.tableStyle.headerCellStyle = {
	...thisPageState.greenHouseMethods.headerCellStyle,
	background: 'white',
};
thisPageState.greenHouseMethods.tableStyle.cellStyle = {
	...thisPageState.greenHouseMethods.tableStyle.cellStyle,
	border: 'none',
};
thisPageState.greenHouseMethods.resetQuery = () => {
	// 清空搜索条件
	greenHouseQueryRef.value?.resetFields();
	thisPageState.greenHouseMethods.getDataList();
};

/**
 * 右边设备的方法
 *
 *
 */
if(thisPageState.deviceState.queryForm.greenhouseId ){
  thisPageState.deviceMethods = useTable(thisPageState.deviceState);
  //如果没有选择大棚 则设备列表永远为空
  thisPageState.deviceState.dataList=[]
}else{
  thisPageState.deviceMethods = useTable(thisPageState.deviceState);
}

thisPageState.deviceMethods.resetQuery = () => {
	// 清空搜索条件
	houseDeviceQueryRef.value?.resetFields();
  // 清空多选
  selectDeviceObjs.value = []
	thisPageState.deviceMethods.getDataList();
};

/**
 左边大棚点击后
 */
function selectGreenHouse(greenhouse) {
	thisPageState.deviceState.queryForm.greenhouseId = greenhouse.id;
  //清空设备的搜索条件 重新查询
  thisPageState.deviceMethods.resetQuery()
}

/**
 * 获取所有基地信息
 */
function getBaseInfoList() {
	fetchBaseInfoList().then((res) => {
		console.log(res);
		thisPageState.baseInfoList = res.data.records;
	});
}

getBaseInfoList();

/**
 * 获取所有设备分类信息
 *
 */

function getDeviceCategoryList() {
	fetchDeviceCategoryList().then((res) => {
		console.log(res);
		thisPageState.deviceCategoryList = res.data.records;
	});
}

getDeviceCategoryList();

/**
 * 获取在线状态和绑定状态的字典
 */
const { iot_device_online_status_dict, iot_device_bind_status_dict } = useDict('iot_device_online_status_dict', 'iot_device_bind_status_dict');


/**
 * 绑定新设备 弹出框
 */
// 引入组件
const FormDeviceDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义变量内容
const formDeviceDialogRef = ref()

/**
 * 已绑定设备多选
 */
// 多选变量
const selectDeviceObjs = ref([]) as any
const multipleDevice = ref(true)

// 多选事件
const selectionDeviceChangHandle = (objs: { id: string }[]) => {
  selectDeviceObjs.value = objs.map(({ id }) => {
    return {
      greenhouseId:thisPageState.deviceState.queryForm.greenhouseId,
      deviceId:id,
    }
  });
  multipleDevice.value = !objs.length;
};

/**
 * 已绑定设备导出
 */
// 导出excel
const exportBindDeviceExcel = () => {
  thisPageState.deviceMethods.downBlobFile('/duorou/duorouGreenhouseDevice/export',Object.assign(thisPageState.deviceState.queryForm, { ids: selectDeviceObjs }), 'duorouGreenhouseDevice.xlsx')
}




// 删除操作
const handleBindDeviceDelete = async (houseDeviceList: []) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delHouseDeviceObjs(houseDeviceList);
    thisPageState.deviceMethods.getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};





/**
 * 跳转到 设备实时运行数据界面
 */
function gotoDeviceRunData(iotDevice,greenhouseId){
  router.push({path:"/iot/iotDevice/deviceRunData/index",query:{iotDeviceId:iotDevice.id,greenhouseId:greenhouseId}})
}

</script>

<style lang="scss" scoped>
.layout-padding {
	.pane_title {
		font-size: medium;
		padding: 5px 0;
	}

	.left_greenhouse {
		:deep(.el-table) {
			.el-table__header-wrapper {
				display: none;
			}

			.el-table__inner-wrapper:before {
				display: none;
			}
		}

		.greenhouse_item_wrap {
			--el-tree-node-hover-bg-color: var(--el-fill-color-light);
			--el-tree-text-color: var(--el-text-color-regular);
			--el-tree-expand-icon-color: var(--el-text-color-placeholder);

			.house_item {
				display: flex;
				justify-content: space-around;
				font-size: 14px;
				color: var(--el-tree-text-color);
				padding: 8px 0;
				cursor: pointer;
			}

			.house_item_active {
				background-color: var(--el-color-primary-light-9);
			}

			.house_item:hover {
				background-color: var(--el-tree-node-hover-bg-color);
			}
		}
	}
}
</style>
